import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:news/com.comm/page/dialog_ui.dart';
import 'package:news/com.comm/utils/StringUtils.dart';
import 'package:news/com.comm/utils/utils.dart';
import 'package:news/com.comm/utils/widget_utils.dart';

import '../contants/writer_type.dart';
import '../model/db_utils.dart';
import '../utils/ApiUtils.dart';

/**
 * 翻译工具首页
 */
class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomeState();
  }
}

class _HomeState extends State {
  final TextEditingController _controller_res_path = TextEditingController();
  final TextEditingController _controller_input = TextEditingController();
  final TextEditingController _controller_out = TextEditingController();
  final db = DbUtils();
  final customFontFamily = "CustomFont${Random().nextInt(1000)}";

  @override
  void initState() {
    super.initState();
    _controller_out.addListener(_handleTextChange);
  }

  void _handleTextChange() {
    // // 假设原始文本编码为GBK，这里将其转换为UTF-8
    // // 注意：这里的编码转换只是一个示例，实际情况可能需要根据具体编码进行调整
    // String originalText = _controller_out.text;
    // if (originalText.isNotEmpty) {
    //   String text = _controller_out.text;
    //   setState(() {
    //     Uint8List bytes = utf8.encode(text);
    //     Uint8List utf8Encoded = utf8.encode(originalString);
    //   });
    // }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Padding(
            padding: EdgeInsets.all(12),
            child:
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Row(
                children: [
                  Expanded(
                      flex: 1,
                      child: TextField(
                        enabled: false,
                        controller: _controller_res_path,
                        // 使用TextEditingController来管理TextField的值
                        decoration: InputDecoration(
                          labelText: '请选择多语言写入路径',
                          hintText: '请选择多语言写入路径',
                          border: OutlineInputBorder(),
                        ),
                      )),
                  SizedBox(
                    child: IconButton(
                      icon: Icon(Icons.more_horiz_rounded),
                      onPressed: () async {
                        showSelectResPathDialog(context);
                      },
                    ),
                    width: 70,
                  ),
                  SizedBox(
                    child: IconButton(
                      icon: Icon(Icons.add),
                      onPressed: () {
                        _addResPath();
                      },
                    ),
                    width: 70,
                  ),
                  SizedBox(
                    child: IconButton(
                      icon: Icon(Icons.delete),
                      onPressed: () {
                        db.delResListPath();
                        showToast("删除多语言路径成功！");
                      },
                    ),
                    width: 70,
                  ),
                  SizedBox(
                    child: IconButton(
                      icon: Icon(Icons.settings),
                      onPressed: () {
                        showTranslateGlobalSetDialog(context);
                      },
                    ),
                    width: 70,
                  ),
                ],
              ),
              SizedBox(
                height: 16,
              ),
              TextField(
                controller: _controller_input,
                // 使用TextEditingController来管理TextField的值
                decoration: InputDecoration(
                  labelText: '请输入翻译内容',
                  hintText: '请输入翻译内容',
                  border: OutlineInputBorder(),
                ),
              ),
              SizedBox(
                height: 12,
              ),
              getTextWidget(16, "翻译工具", Colors.black),
              SizedBox(
                height: 4,
              ),
              Row(
                children: [
                  SizedBox(
                      height: 40,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                          ),
                          onPressed: () {
                            _translateByIciBaLocal(context);
                          },
                          child: getTextWidget(16, "爱词霸翻译(快)", Colors.white))),
                ],
              ),
              SizedBox(
                height: 12,
              ),
              getTextWidget(16, "文本操作", Colors.black),
              SizedBox(
                height: 4,
              ),
              Row(
                children: [
                  SizedBox(
                      height: 40,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                          ),
                          onPressed: () {
                            _writeTranslate();
                          },
                          child: getTextWidget(16, "写入翻译", Colors.white))),
                  SizedBox(
                    width: 8,
                  ),
                  SizedBox(
                      height: 40,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                          ),
                          onPressed: () {
                            _replaceTranslate();
                          },
                          child: getTextWidget(16, "替换翻译", Colors.white))),
                  SizedBox(
                    width: 8,
                  ),
                  SizedBox(
                      height: 40,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                          ),
                          onPressed: () {
                            _removeTranslate();
                          },
                          child: getTextWidget(16, "移除翻译", Colors.white))),
                  SizedBox(
                    width: 8,
                  ),
                  SizedBox(
                      height: 40,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                          ),
                          onPressed: () {
                            _showKeyTranslateLanguages();
                          },
                          child: getTextWidget(16, "预览翻译", Colors.white))),
                  SizedBox(
                    width: 8,
                  ),
                  SizedBox(
                      height: 40,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                          ),
                          onPressed: () {
                            _exportLanguages();
                          },
                          child: getTextWidget(16, "导出翻译", Colors.white))),
                  SizedBox(
                    width: 8,
                  ),
                  SizedBox(
                      height: 40,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                          ),
                          onPressed: () {
                            _parseLanguages();
                          },
                          child: getTextWidget(16, "解析多语言", Colors.white))),
                ],
              ),
              SizedBox(
                height: 16,
              ),
              getTextWidget(16, "翻译结果", Colors.black),
              SizedBox(
                height: 4,
              ),
              Container(
                  constraints: BoxConstraints(
                    maxHeight: 343.0, // 设置最大高度
                  ),
                  child: TextField(
                    maxLines: null,
                    minLines: 18,
                    controller: _controller_out,
                    style: TextStyle(
                      fontSize: 18.0,
                      fontFamily: customFontFamily,
                    ),
                    // 使用TextEditingController来管理TextField的值
                    decoration: InputDecoration(
                      hintText: '翻译内容空空如也~~~',
                      border: OutlineInputBorder(),
                    ),
                  )),
            ])));
  }

  /**
   * 爱词霸翻译  本地API 调用
   */
  void _translateByIciBaLocal(BuildContext context) async {
    String inputTranslateText =
        _controller_input.text.toString().trim().replaceAll("\r", "");
    if (inputTranslateText.isEmpty) {
      showToast("请输入需要翻译的文案");
      return;
    }
    showLoadingDialog(context, () {}, loadingText: "正在翻译中...");
    if (inputTranslateText.contains("\\n")) {
      inputTranslateText = inputTranslateText.replaceAll("\\n", "@");
    }

    ApiUtils.getTranslateByIciBaLocal(inputTranslateText, (result) {
      if (result.toString().isEmpty) {
        return;
      }
      // 使用 jsonEncode 函数进行格式化输出
      String prettyPrint = JsonEncoder.withIndent('  ').convert(result);
      setState(() {
        _controller_out.text = prettyPrint;
      });
      Navigator.of(context).pop();
    });
  }

  /**
   * 显示选择多语言路径弹窗
   */
  void showSelectResPathDialog(BuildContext context) async {
    String? arrString = await db.loadResListPath();
    if (arrString != null && arrString.isNotEmpty) {
      debugPrint("arrString:${arrString}");
      var map = await jsonDecode(arrString);
      List<String> list = map.keys.toList();
      showResListSelectDialog(context, "选择多语言写入路径", list, (path) {
        debugPrint("选择的路径:${path}");
        setState(() {
          _controller_res_path.text = map[path];
        });
      });
    } else {
      showToast("请先添加多语言写入路径");
    }
  }

  /**
   * 新增多语言路径
   */
  void _addResPath() {
    showAddResPathDialog(context, "新增多语言路径", (key, value) async {
      debugPrint("key：${key}|value:${value}");
      await db.saveResListPath(key, value);
      showToast("新增成功！");
    });
  }

  /**
   * 写入翻译
   */
  void _writeTranslate() {
    String transResult = _controller_out.text.trim();
    String resPath = _controller_res_path.text.trim();
    if (resPath.isEmpty) {
      showToast("多语言写入路径不能为空！");
      return;
    }
    if (transResult.isEmpty) {
      showToast("翻译内容不能为空！");
      return;
    }
    var transMap = jsonDecode(transResult);
    String translateKey = StringsUtils.getTranslateKey(transMap["en"]);
    showWriteTranslateSureKeyDialog(
        context, "请确认要写入的多语言翻译key", translateKey, true, "写入", (key) async {
      debugPrint("key：${key}");
      if (StringsUtils.isExistTranslateKey(resPath, key)) {
        //已存在
        showWriteTranslateSureKeyDialog(
            context, "翻译key已存在,是否替换？", key, false, "替换", (newKey) async {
          debugPrint("key：${newKey}");
          //先移除
          await StringsUtils.removeTranslateByKey(resPath, key);
          //再插入
          await StringsUtils.startInsertLanguage(
              newKey, transMap, resPath, WriterType.insert);
          showToast("翻译替换成功！");
        });
      } else {
        StringsUtils.startInsertLanguage(
            key, transMap, resPath, WriterType.insert);
        showToast("翻译写入成功！");
      }
    });
  }

  /**
   * 预览翻译
   */
  void _showKeyTranslateLanguages() {
    String resPath = _controller_res_path.text.trim();
    if (resPath.isEmpty) {
      showToast("多语言预览路径不能为空！");
      return;
    }
    showTranslateShowDialog(context, resPath);
  }

  /**
   *导出翻译
   */
  void _exportLanguages() {
    String resPath = _controller_res_path.text.trim();
    if (resPath.isEmpty) {
      showToast("多语言导出路径不能为空！");
      return;
    }
    showExportLanguageDialog(context, resPath);
  }

  /**
      解析多语言
   */
  void _parseLanguages() {
    String resPath = _controller_res_path.text.trim();
    if (resPath.isEmpty) {
      showToast("多语言导出路径不能为空！");
      return;
    }
    showParseTranslateShowDialog(context, resPath);
  }

  /**
   * 替换翻译
   */
  void _replaceTranslate() {
    String transResult = _controller_out.text.trim();
    String resPath = _controller_res_path.text.trim();
    if (resPath.isEmpty) {
      showToast("多语言写入路径不能为空！");
      return;
    }
    if (transResult.isEmpty) {
      showToast("翻译内容不能为空！");
      return;
    }
    var transMap = jsonDecode(transResult);
    String translateKey = StringsUtils.getTranslateKey(transMap["en"]);
    showWriteTranslateSureKeyDialog(
        context, "请确认要替换的多语言翻译key", translateKey, true, "替换", (key) async {
      debugPrint("key：${key}");
      if (!StringsUtils.isExistTranslateKey(resPath, key)) {
        showToast("要替换的翻译key不存在！");
      } else {
        //先移除
        await StringsUtils.removeTranslateByKey(resPath, key);
        //再插入
        await StringsUtils.startInsertLanguage(
            key, transMap, resPath, WriterType.insert);
        showToast("翻译替换成功！");
      }
    });
  }

  /**
   * 移除翻译
   */
  void _removeTranslate() {
    String resPath = _controller_res_path.text.trim();
    if (resPath.isEmpty) {
      showToast("多语言写入路径不能为空！");
      return;
    }
    showWriteTranslateSureKeyDialog(context, "请确认需要移除的多语言key", "", true, "移除",
        (key) async {
      debugPrint("key：${key}");
      if (!StringsUtils.isExistTranslateKey(resPath, key)) {
        showToast("要移除的翻译key不存在！");
      } else {
        StringsUtils.removeTranslateByKey(resPath, key);
        showToast("翻译移除成功！");
      }
    });
  }

  @override
  void dispose() {
    _controller_res_path.dispose(); // 释放控制器资源
    _controller_out.dispose(); // 释放控制器资源
    _controller_input.dispose(); // 释放控制器资源
    super.dispose();
  }
}
